package warthog.parsegen;

import java.util.Arrays;
import java.util.Collection;

import warthog.cradle.JavaClass;

/**
 * The main purpose this class seems to serve is to organize the terminals and
 * nonterminals into two separate arrays, and then also to assign id numbers to
 * each symbol based on its position within these arrays.
 * 
 * Originally, this class was also involved in some of the things which
 * warthog.cradle.JavaClass now is responsible for. And, in light of all that,
 * it might make sense to grow this class more toward writing all the code, and
 * thus get the Generator class out of that business and more strictly about
 * computing the handle-finding automaton.
 * 
 * Or, it might make more sense to grow this class more towards managing an
 * alphabet of symbols, independently of their later use in making an HFA.
 * 
 * @author Ian
 * 
 */
public class GeneratorData {
	
	Sym[] terms, nonterms;
	
	public GeneratorData() { }
	/**
	 * 
	 * @param in
	 */
	public void prepareSymbols(Collection<Sym> in) {
		int numTerms = 0;
		int numNonterms = 0;
		for (Sym s:in) {
			if (s.term) numTerms++;
			else numNonterms++;
		}
		terms = new Sym[numTerms];
		nonterms = new Sym[numNonterms];
		for (Sym s:in) {
			if (s.term) terms[--numTerms] = s;
			else nonterms[--numNonterms] = s;
		}
		Arrays.sort(terms);
		Arrays.sort(nonterms);
		enumerate(terms);
		enumerate(nonterms);
	}

	private static void enumerate(Sym[] syms) {
		for (int i=0; i<syms.length; i++) syms[i].id = i;
	}
	
	public void writeStaticFinalFields(JavaClass cw) {
		for (Sym s:terms) if (s.name!=null) {
			cw.codeln("public static final int t_"+s.name+" = "+s.id+";");
		}
	}
	
	public void makeSemanticCheckArray(JavaClass cw) {
		cw.code("private final int[] yy_sc = {");
		for (Sym s:terms) cw.code(s.semanticClass.id+", ");
		cw.codeln("};");
	}
}